package com.huaxindata.im.main.contactview.group;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxindata.common.util.DialogUtil;
import com.huaxindata.common.util.ToastUtil;
import com.huaxindata.im.R;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.db.ContactStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatSysMessageBody;
import com.huaxindata.im.service.MessageService;
import com.huaxindata.im.util.Log;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 填写群资料，创建群的界面
 */
public class CreateGroupActivity extends AppCompatActivity implements
        View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    public static final String TAG = "CreateGroupActivity";
    private Toolbar  mToolbar;
    private Button   mSubmitBtn;
    private EditText mGroupTitleEt;
    private CheckBox mCheckBox;//勾选同意服务协议的
    int itemWith;
    int itemOffset;
    private LinearLayout mGroupMemberLayout;
    TextView  group_people_info;
    String    groupInfo;
    File      file;
    ImageView new_group_icon;
    private List<Contact> mSelectedList;


    private boolean mIsBind = false;
    private MessageService mMessageService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
        bindToService();
        initView();
        initData();
    }

    private void initView() {
        mSubmitBtn = (Button) findViewById(R.id.create_group_confirm);
        mGroupTitleEt = (EditText) findViewById(R.id.create_group_name_et);
        mCheckBox = (CheckBox) findViewById(R.id.create_group_checkbox);
        mToolbar = (Toolbar) findViewById(R.id.create_group_toolbar);
        mGroupMemberLayout = (LinearLayout) findViewById(R.id.create_group_member_layout);
        group_people_info = (TextView) findViewById(R.id.create_group_member_info);
        new_group_icon = (ImageView) findViewById(R.id.create_group_icon);
        setSupportActionBar(mToolbar);
        mToolbar.setTitle("创建群");
        mSubmitBtn.setOnClickListener(this);
        mGroupTitleEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                updateButtonState();
            }
        });
        mCheckBox.setOnCheckedChangeListener(this);

        final int screenW = getResources().getDisplayMetrics().widthPixels;
        itemWith = screenW / 10;//最多7个
        itemOffset = itemWith * 3 / 8;
    }

    /**
     * 默认只显示四个群成员
     */
    private void initData() {
        mSelectedList = SelectMemberPresenter.getSelectedList();
        groupInfo = getResources().getString(R.string.new_group_people_select);
        group_people_info.setText(String.format(groupInfo, mSelectedList.size()));
        mGroupMemberLayout.removeAllViewsInLayout();
        if (mSelectedList != null && mSelectedList.size() > 0) {
            for (int i = 0; i < mSelectedList.size(); i++) {
                if (i > 4) {
                    break;
                } else {
                    Contact contact = mSelectedList.get(i);
                    View root = LayoutInflater.from(this).inflate(R.layout.group_member_simple_item, null);
                    AvatarImageView icon = (AvatarImageView) root.findViewById(R.id.group_member_simple_icon);
                    TextView iv_icon_expand = (TextView) root.findViewById(R.id.group_member_simple_icon_tv);
                    setParamsWithType(icon, iv_icon_expand);
                    contact.showImageIcon(this, icon, iv_icon_expand);
                    mGroupMemberLayout.addView(root, i);
                }
            }
        }
        mGroupMemberLayout.requestLayout();
        updateButtonState();
    }

    /**
     * 绑定到后台接收消息的service
     */
    private void bindToService() {
        Intent intent = new Intent(this, MessageService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        mIsBind = true;
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessageService = ((MessageService.MyBinder) service).getService();
            mIsBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMessageService = null;
            mIsBind = false;
        }
    };

    private void unBindService() {
        if (mIsBind) {
            unbindService(mServiceConnection);
            mIsBind = false;
        }
    }

    /**
     * 给指定的view设置参数
     *
     * @param tags
     */
    private void setParamsWithType(View... tags) {
        for (View tag : tags) {
            setParamsWithType(tag);
        }
    }

    private void setParamsWithType(View view) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.width = params.height = itemWith;
        params.leftMargin = itemOffset;
        view.setLayoutParams(params);
    }

    /**
     * 如果没有填写群名称以及群名称太短是不能提交的
     */
    private void updateButtonState() {
        if (!mCheckBox.isChecked() || TextUtils.isEmpty(mGroupTitleEt.getText()) || mGroupTitleEt.getText().length() < 2) {
            mSubmitBtn.setEnabled(false);
            mSubmitBtn.setBackgroundResource(R.drawable.gray_shape_rect);

        } else {
            mSubmitBtn.setEnabled(true);
            mSubmitBtn.setBackgroundResource(R.drawable.blue_shape_rect);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.create_group_confirm) {
            //创建群组
            createGroup();
        } else if (id == R.id.create_group_icon) {
            //此处需要图片选择器配合
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        updateButtonState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private Dialog dialog;

    /**
     * 提交建群资料到服务器
     */
    public void createGroup() {
        if (dialog == null) {
            dialog = DialogUtil.getWaitDialog(this, "申请中");
        }
        dialog.setCanceledOnTouchOutside(false);
        if (dialog.isShowing()) {
            return;
        }
        dialog.show();
        final String name = mGroupTitleEt.getText().toString();
        final StringBuilder sb = new StringBuilder();
        sb.append(UserManager.getClientId());
        for (int i = 0; i < mSelectedList.size(); i++) {
            sb.append(",");
            sb.append(mSelectedList.get(i).getClientId());
        }

        MultipartBody.Part part = null;

        //群头像
        if (file != null) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        }

        final Callback<ContactGroup> callback = new Callback<ContactGroup>() {
            @Override
            public void onResponse(Call<ContactGroup> call, Response<ContactGroup> response) {
                ContactGroup group = response.body();
                if (response.isSuccessful() && group != null) {
                    ToastUtil.showToast(CreateGroupActivity.this, "创建成功");
                    Log.e("lwjing","创建群 "+group.toString());
                    ContactManager.initData();//建群成功后更新本地群数据
                    //向服务器申请建群成功后发送系统信息
                    sendCreateGroupSystemMessage(group);
                    ContactStore.insert(group, 2, System.currentTimeMillis());
                    setResult(ImConstants.RESULT_CODE_EXIT);
                    finish();
                } else {
                    ToastUtil.showToast(CreateGroupActivity.this, "创建失败");
                }
                dialog.dismiss();

            }

            @Override
            public void onFailure(Call<ContactGroup> call, Throwable t) {
                dialog.dismiss();
                if (t != null)
                    t.printStackTrace();
                ToastUtil.showToast(CreateGroupActivity.this, "创建失败");
            }
        };
        //异步向服务器提交创建群的信息
        if (part == null) {
            Log.e("lwjing","clientid "+sb.toString()+" name="+name);
            RetrofitClient.getHttpApi().createGroup(name, sb.toString()).enqueue(callback);
        } else {
            RetrofitClient.getHttpApi().createGroupWithPic(part, name, sb.toString()).enqueue(callback);
        }
    }

    /**
     * 建群成功之后向所有群成员发送消息
     * 消息内容格式："createGroup #& 群id #& 群名称 #& 群主id #& 群成员id #& 群头像"
     *
     * @param group
     */
    private void sendCreateGroupSystemMessage(ContactGroup group) {
      //  String[] membersId = group.getGroupMembers().split(",");
        String[] membersId = group.getGroupMemberId();
        for (String id : membersId) {
            ChatMessage message = new ChatMessage(ChatMessageBody.Type.SYSTEM, group.groupClientId, id, System.currentTimeMillis());
            ChatSysMessageBody chatSysMessageBody = new ChatSysMessageBody(ChatMessageBody.Type.SYSTEM);
            chatSysMessageBody.action = ChatSysMessageBody.SysMessageType.ACTION_CREATE_GROUP;
            chatSysMessageBody.content = chatSysMessageBody.action + ChatMessage.PREX + group.toString();
            message.messageBody = chatSysMessageBody;
            sendMessage(message,group,id);
        }
        mMessageService.subscribe(group.groupClientId);
    }

    private void sendMessage(final ChatMessage message, final ContactGroup group, final String id) {
        String topic = "chat/" + message.receiver;
        mMessageService.sendMessage(topic, message,null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        unBindService();
    }
}
